package cn.actoncode.boot.module.ai.dal.redis.auth;

import cn.actoncode.boot.framework.common.util.json.JsonUtils;
import cn.actoncode.boot.framework.security.core.LoginUser;
import cn.actoncode.boot.module.ai.dal.redis.RedisKeyConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

@Slf4j
@Repository
public class LoginUserRedisDAO {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public LoginUser get(Long userId) {
        String redisKey = formatKey(userId);
        return JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(redisKey), LoginUser.class);
    }

    public void set(LoginUser loginUser) {
        String redisKey = formatKey(loginUser.getUserId());
        stringRedisTemplate.opsForValue().set(redisKey, JsonUtils.toJsonString(loginUser));
    }

    public void delete(Long userId) {
        String redisKey = formatKey(userId);
        stringRedisTemplate.delete(redisKey);
    }

    private static String formatKey(Long userId) {
        return String.format(RedisKeyConstants.LOGIN_USER_CODE, userId);
    }
}
